<script setup name="sub-category">
import { ref, watchEffect, computed } from 'vue';
import { useRoute, onBeforeRouteUpdate, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { arr } from '@/constants/custom-data.js';
import sortButton from '@/components/sort-btn/index.vue';

const store = useStore();
const route = useRoute();
const router = useRouter();
const filterList = computed(() => store.state.liviinghome.filterList);
const currentPage = ref(1);

function init(to) {
  const params = {
    page: currentPage.value,
    pageSize: 10,
    categoryId: to.params.id,
  };
  store.dispatch('liviinghome/updateSubGoods', params);
  store.dispatch('liviinghome/updateFilter', to.params.id);
}
// 初始化请求
init(route);
// 路由id变化时, 重新请求
onBeforeRouteUpdate(init);
const subgoodsList = computed(() => store.state.liviinghome.subgoodsList);

// 记录
let observer = null;
let lastObserver = null;

const hasNext = computed(() => subgoodsList.value.pages > currentPage.value);

watch(subgoodsList, async () => {
  if (!hasNext.value) {
    return;
  }
  await nextTick();
  // 取消上一轮的观察
  if (observer) {
    observer.unobserve(lastObserver);
  }
  // 当clothes滚动到视野中时, dispatch
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        // 应该自己写的内容
        const params = {
          page: ++currentPage.value,
          pageSize: 10,
          categoryId: route.params.id,
        };
        store.dispatch('liviinghome/updateSubGoods', params);
      }
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5,
    },
  );
  lastObserver = document.querySelector('.card-content:last-child');
  // 启动观察clothes.value是否进入视野
  observer.observe(lastObserver);
});
// 引入名为subCategoryFilters的getters
const subCategoryFilters = ref([]);
const subCategoryFiltersAttrs = ref([]);

watch(
  () => store.getters['liviinghome/subFilterList'],
  () => {
    subCategoryFilters.value = store.getters['liviinghome/subFilterList'].map((d) => ({
      ...d,
      properties: [
        {
          id: 'all',
          name: '全部',
        },
        ...d.properties,
      ],
    }));
    subCategoryFiltersAttrs.value = store.getters['liviinghome/subFilterList'].map((d) => ({
      groupName: d.name,
      propertyName: '全部',
    }));
  },
);
async function onFilterChange() {
  await nextTick();
  const attrs = subCategoryFiltersAttrs.value.filter((d, i) => d.propertyName !== '全部' && i > 0);
  const params = {
    brandId: store.state.liviinghome.filterList.brands.find((b) => b.name === subCategoryFiltersAttrs.value[0].propertyName)?.id || null,
    attrs,
    page: currentPage.value,
    pageSize: 10,
    categoryId: route.params.id,
  };
  store.dispatch('liviinghome/resetSubGoods', params);
}
// 有货商品
const goods = ref(false);
// 特惠商品
const discounts = ref(false);
// 价格排序
const price = ref(false);
// 切换筛选
const toggle = ref(false);
function onChange(i) {

}

const sortType = ref('');
// 排序
function onSort() {
  toggle.value = true;
  price.value = !price.value;
  currentPage.value = 1;
  const params = {
    page: 1,
    pageSize: 10,
    categoryId: route.params.id,
  };
  store.dispatch('liviinghome/resetSubGoods', params);
  if (toggle.value) {
    if (price.value) {
      const subgoodsList = computed(() => store.state.liviinghome.subgoodsList);
      const stop = watchEffect(() => {
        subgoodsList.value.items.sort((a, b) => a.price - b.price);
      });
      // 打断watchEffect
      if (!toggle.value) {
        console.log(1111);
        stop();
      }
    } else {
      const subgoodsList = computed(() => store.state.liviinghome.subgoodsList);
      watchEffect(() => {
        subgoodsList.value.items.sort((a, b) => b.price - a.price);
      });
      if (!toggle.value) {
        console.log(2222);
        stop();
      }
    }
  }
}

// 显示特惠产品
function fn() {
  const params = {
    categoryId: '1005009',
    inventory: false,
    onlyDiscount: true,
    page: 1,
    pageSize: 20,
    sortField: null,
    sortMethod: null,
  };
  store.dispatch('liviinghome/resetSubGoods', params);
}

watch(() => discounts.value, () => {
  // console.log(discounts.value);
  if (discounts.value) {
    fn();
  }
});

const arrList = computed(() => arr);

// 变换背景色
function onChangeColor(name) {
  toggle.value = false;
  watchEffect(() => {
    arrList.value.forEach((item, c) => {
      if (item.name === name) {
        item.config = true;
      } else {
        item.config = false;
      }
    });
    currentPage.value = 1;
    const params = {
      page: 1,
      pageSize: 10,
      categoryId: route.params.id,
    };
    store.dispatch('liviinghome/resetSubGoods', params);
  });
}
// 跳转到详情页
function goJump(id) {
  router.push({
    name: '三级分类',
    params: {
      id,
    },
  });
}
</script>

<template>
  <div class="main">
    <!-- 面包屑 -->
    <div class="crumbs">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/livinghome/${ filterList.parentId }` }">{{ filterList.parentName }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/category/sub/${ filterList.id }` }">{{ filterList.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 商品选项 -->
    <div class="product-container">
      <el-form>
        <el-form-item
          v-for="(item, i) in subCategoryFilters"
          :key="item.id"
          :label="item.name"
        >
          <el-radio-group
            v-model="subCategoryFiltersAttrs[i].propertyName"
            @change="onFilterChange"
          >
            <el-radio
              v-for="property in item.properties"
              :key="property.id"
              :label="property.name"
            >
              {{ property.name }}
            </el-radio>
          </el-radio-group>

        </el-form-item>
      </el-form>
      <!-- <div class="product-container">
        <div class="product-left">
          <div class="brand">品牌:</div>
          <div class="all">全部</div>
        </div>
        <div class="sub-product">
          <div
            v-for="item in filterList.brands"
            :key="item.id"
            class="product-item"
          >
            <div>{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div
        v-for="item in filterList.saleProperties"
        :key="item.id"
        class="product-container"
      >
        <div class="product-left">
          <div class="brand">{{ item.name }}:</div>
          <div class="all">全部</div>
        </div>
        <div class="sub-product">
          <div class="product-item">
            <div
              v-for="(subItem, i) in item.properties"
              :key="subItem.id"
              @click="onChange(i + 1)"
              class="product-item-color"
              :class="subItem.name.length > 8 ? 'product-size' : ''"
            >
              {{ subItem.name }}
            </div>
          </div>
        </div>
      </div> -->
    </div>

    <!-- 商品图片集 -->
    <div class="product-card-container">
      <div class="product-card-container-title">
        <div class="sort-btn">
          <div
            v-for="(item, i) in arr"
            :key="i"
            @click="onChangeColor(item.name)"
            :class="item.config ? 'sort-item' : ''"
            class="sort"
          >
            {{ item.name }}
          </div>
          <div
            @click="onSort"
          >价格排序</div>
          <sort-button
            v-model:value="sortType"
          >
            价格排序
          </sort-button>
        </div>
        <div>
          <el-checkbox v-model="goods"><span>仅显示有货商品</span></el-checkbox>
          <el-checkbox v-model="discounts"><span>仅显示特惠商品</span></el-checkbox>
        </div>
      </div>
      <!-- 小卡片 -->
      <div
        v-show="subgoodsList.items.length"
        class="card-content-container">
        <div
          v-for="item in subgoodsList.items"
          :key="item.id"
          @click="goJump(item.id)"
          class="card-content animation"
        >
          <div>
            <img class="img" :src="item.picture">
          </div>
          <div class="sub-name">{{ item.name }}</div>
          <div class="sub-name sub-desc">{{ item.desc }}</div>
          <p>￥{{ item.price }}</p>
        </div>
      </div>
      <div
        v-show="!hasNext"
      >
        <el-empty description="亲，没有更多了"/>
      </div>

    </div>
  </div>
</template>

<style lang="scss" scoped>
  $white: white;
.main {
  padding: 0 130px;

  .crumbs {
    // 公共样式面包屑
    @include crumbs();
  }

  // 商品选项
  .product-container {


    // background-color: $white;
    // display: flex;
    // font-size: 14px;
    // .product-left {
    //   display: flex;
    //       // 品牌
    //   .brand {
    //     width: 60px;
    //     color: #999999;
    //     padding: 12px 10px;
    //   }

    //   .all {
    //     padding: 12px 0;
    //     width: 50px;
    //     color: $c;
    //   }
    // }


    // 子商品
    // .sub-product {
    //   display: flex;
    //   font-size: 14px;

    //   .product-item {
    //     display: flex;
    //     flex-wrap: wrap;

    //     &>div {
    //       margin-right: 36px;
    //       padding: 12px 0;
    //       color:#333333;
    //       cursor: pointer;

    //       &:hover {
    //         color: $c;
    //       }
    //     }

    //     .product-size {
    //       @include text-ellipsis();
    //     }
    //   }
    // }
  }

  // 商品图片集
  .product-card-container {
    background-color: $white;
    margin-top: 22px;
    height: 100%;

    // 商品图片集标题
    .product-card-container-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 0;
      border-bottom: 1px solid #e5e5e5;

      .sort-btn {
        display: flex;
        font-size: 14px;
        color: #333333;
        padding-left: 10px;

        .sort-item {
          background-color: $c;
          color: $white;
        }

        &>div {
          margin-right: 20px;
          color: #999;
          border: 1px solid #999;
          padding: 4px 8px;
          border-radius: 2px;

          &:hover {
            cursor: pointer;
          }
        }
      }

      div:nth-child(2) {
        padding-right: 10px;


        span {
          color: #999;
        }
      }
    }

    .card-content-container {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      height: 100%;
      padding: 0 10px;
      // 上下有间隔
      grid-row-gap: 20px;
      // 左右有间隔
      grid-column-gap: 20px;

      .card-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100%;
        margin-top: 12px;

        img {
          margin-top: 12px;
          width: 100px;
          display: block;
          object-fit: cover;
        }

        .img {
          width: 160px;
          display: block;
          object-fit: cover;
        }

        .sub-name {
          padding-top: 8px;
          text-align: center;
          width: 160px;
          color: #333;
          // 文字省略号
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .sub-desc {
          color: #999999;
          font-size: 14px;
        }

        p {
          color: red
        }

        &:hover {
          color: $c;
          cursor: pointer;
        }
      }

      // 小卡片鼠标移入动画
      .animation {
        transform: translateY(0px);
        box-shadow: 0 0 0px 0 rgba(0, 0, 0, 0);
        transition: all 0.3s linear;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.3);
        }
      }
    }
  }
}
:deep(.el-form-item__label) {
  width: 70px;
  justify-content: normal;
}

:deep(.el-radio__inner) {
  display: none;
}
</style>
